import 'dart:async';

import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:videotop/base_model.dart';
import 'package:videotop/jsonbean/spacebean.dart';
import 'package:videotop/myinfo.dart';
import 'package:videotop/sql/databasehelper.dart';
import 'package:videotop/sql/user_table.dart';
import 'package:videotop/util.dart';
import 'package:videotop/widget/buygold.dart';
import 'package:videotop/widget/chat.dart';
import 'package:videotop/widget/videoPage.dart';
import 'package:shake_animation_widget/shake_animation_widget.dart';
import 'package:video_player/video_player.dart';

import '../evenbus.dart';

/// created by hx
///    2021/1/27:9:48

class SpaceModel extends BaseModel{

  int uid;
  int type;
  MyInfo myInfo;
  Util util;
  BuildContext context;
  SpaceModel(this.uid, this.type, this.myInfo, this.util, this.context);

  SpaceUser user;
  VideoPlayerController controller;
  Future videoPlayFuture;

  bool isload = true;

  List img = [];

  ///抖动动画控制器
  ShakeAnimationController shakeAnimationController =
  new ShakeAnimationController();

  ///构建抖动效果
  ShakeAnimationWidget buildShakeAnimationWidget() {
    return ShakeAnimationWidget(
      ///抖动控制器
      shakeAnimationController: shakeAnimationController,

      ///微旋转的抖动
      shakeAnimationType: ShakeAnimationType.RoateShake,

      ///设置不开启抖动
      isForward: false,

      ///默认为 0 无限执行
      shakeCount: 0,

      ///抖动的幅度 取值范围为[0,1]
      shakeRange: 0.2,

      ///执行抖动动画的子Widget
      child: Image.asset(
        'assets/image/video1.png',
        width: 20,
      ),
    );
  }

  getVideo() {
    if (user.video.isNotEmpty) {
      controller = VideoPlayerController.network(user.video);
      videoPlayFuture = controller.initialize();
      notifyListeners();
    }
  }

  void getSpace() async {
    try {
      user = await util.getuserinfo(uid);
      img = user.img;
      getPubgins();
      isload = false;
      Timer(Duration(seconds: 1), () {
        shakeAnimationController.start(shakeCount: 200);
      });
      notifyListeners();
      getVideo();
    } catch (e) {
      print(e);
    }
  }

  List<Widget> pubgins = [];
  int pod = 0;
  SwiperController swipercontroller = SwiperController();

  getPubgins() {
    pubgins.clear();
    for (int i = 0; i < img.length; i++) {
      pubgins.add(Expanded(
        child: Container(
          margin: EdgeInsets.only(left: 3, right: 3),
          height: 5,
          color: pod == i ? Colors.white : Color(0x5F9E9E9E),
        ),
      ));
    }
    notifyListeners();
  }

  handleCameraAndMic() async {
    if(controller != null){
      if(controller.value.isPlaying){
        controller.pause();
      }
    }
    Map<String, dynamic> map = {'yuid': uid, 'vip': myInfo.vip};
    if (myInfo.gold < user.price) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (context) => BuyGold()));
    } else {
      util.requestCamera(context).then((value) {
        if (value) {
          util.requestVoice(context).then((value) {
            if (value) {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return VideoPage(
                  true,
                  price: user.price,
                  uid: user.uid,
                  role: ClientRole.Broadcaster,
                  channelName: '${myInfo.uid}_${user.uid}',
                  nickname: user.nickname,
                  icon: user.icon,
                  country: user.country,
                  countrycode: user.code,
                  vip: user.vip,
                  birth: user.birth,
                );
              }));
            } else {
              util.showToast('Microphone permission required');
            }
          });
        } else {
          util.showToast('Camera permission required');
        }
      });
    }
  }

  goChat() async {
    Map<String, dynamic> map = {'yuid': uid, 'vip': myInfo.vip};
    var db = DatabaseHelper();
    UserTable usertable = await db.getItem(user.uid);
//    UserTable usertable = await db.getItem(728332);
    if (usertable == null) {
      usertable = new UserTable();
      usertable.nickname = user.nickname;
      usertable.icon = user.icon;
      usertable.uptime = DateTime.now().millisecondsSinceEpoch.toString();
      usertable.uid = user.uid;
      usertable.country = user.country;
      usertable.code = user.code;
      usertable.vip = user.vip;
      usertable.birth = user.birth;
      usertable.price = user.price;
      usertable.times = DateTime.now().millisecondsSinceEpoch.toString();
      db.saveItemUser(usertable);
    } else {
      var nowtime = DateTime.now();
      if (DateTime.fromMillisecondsSinceEpoch(int.parse(usertable.uptime))
          .add(Duration(hours: 1))
          .isBefore(nowtime)) {
        UserTable user = new UserTable();
        user.uid = user.uid;
        user.times = DateTime.now().millisecondsSinceEpoch.toString();
        user.icon = user.icon;
        user.uptime = DateTime.now().millisecondsSinceEpoch.toString();
        user.nickname = user.nickname;
        user.country = user.country;
        user.vip = user.vip;
        user.birth = user.birth;
        user.code = user.code;
        user.price = user.price;
        db.updateUser(user);
      }
    }
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => Chat(
              userTable: usertable,
            )));
  }

  //关注
  Future<Null> follow() async {
    try {
      int result = await util.getfollow(1, uid,myInfo.uid);
      if (result == 1) {
        type = 0;
        myInfo.setfollowing(myInfo.following++);
        bus.emit('myrefresh');
        bus.emit('followrefresh');
        notifyListeners();
      } else {}
    } catch (e) {
      print(e);
    }
  }

  getBlack() async {
    List<String> list = util.spfs.getStringList('black') ?? [];
    list.add(uid.toString());
    util.spfs.setStringList('black', list);
    util.showToast('Successful operation');
    Navigator.pop(context);
  }

  @override
  void dispose() {
    if (controller != null) controller.dispose();
    swipercontroller.dispose();
    super.dispose();
    shakeAnimationController.stop();
  }
}